/**
 * 
 */
package com.xbang.attendance.web.loader;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xbang.attendance.entity.system.Menu;
import com.xbang.attendance.utils.ComparatorMenu;
import com.xbang.core.web.loader.ServletContextLoader;

import edu.emory.mathcs.backport.java.util.Collections;

/**
 * @author dev.zhang
 * 
 */
@Component("systemServletContextLoader")
public class SystemServletContextLoader implements ServletContextLoader {

	private static final Log logger = LogFactory.getLog(SystemServletContextLoader.class);

	@Autowired
	private com.xbang.attendance.security.SecurityManager securityManager;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.demo2do.core.web.loader.ServletContextLoader#initServletContext(javax.servlet.ServletContext)
	 */
	public void initServletContext(ServletContext servletContext) {

		if (logger.isDebugEnabled()) {
			logger.debug("Initial ServletContext for system");
		}

		List<Menu> menus = securityManager.listMenus();

		ComparatorMenu comparatorMenu = new ComparatorMenu();
		java.util.Collections.sort(menus, comparatorMenu);

		Map<Integer, List<Menu>> submenus = securityManager.listSubmenus();
		Map<String, String> urlAuthorities = securityManager.listUrlAuthorities();

		servletContext.setAttribute("menus", menus);
		servletContext.setAttribute("submenus", submenus);
		servletContext.setAttribute("urlAuthorities", urlAuthorities);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.demo2do.core.web.loader.ServletContextLoader#closeServletContext(javax.servlet.ServletContext)
	 */
	public void closeServletContext(ServletContext servletContext) {

		if (logger.isDebugEnabled()) {
			logger.debug("Destroying ServletContext for system");
		}

		servletContext.removeAttribute("menus");
		servletContext.removeAttribute("submenus");
	}

}
